//
//  TRJPushHelper.m
//  欣窝互联网(深圳)有限公司
//
//  Created by User on 16/5/20.
//  Copyright © 2016年 张 杰. All rights reserved.
//

#import "TRJPushHelper.h"

#import "NSString+jmCategory.h"

#import "JPUSHService.h"

#import "APIKey.h"

#import <AdSupport/ASIdentifierManager.h>

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

#import <UserNotifications/UserNotifications.h>

#endif

@interface TRJPushHelper ()<JPUSHRegisterDelegate>


@end
static TRJPushHelper *sharedHelper = nil;
@implementation TRJPushHelper
+ (TRJPushHelper *)sharedHelper {
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        sharedHelper = [[TRJPushHelper alloc] init];
    });
    
    return sharedHelper;

}
+ (void)setupWithOptions:(NSDictionary *)launchOptions
{
    // Required
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    // ios8之后可以自定义category
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        // 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
        // ios8之前 categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
#endif
    }
#else
    // categories 必须为nil
    [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                      UIRemoteNotificationTypeSound |
                                                      UIRemoteNotificationTypeAlert)
                                          categories:nil];
#endif
    
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    
    
    [JPUSHService setupWithOption:launchOptions appKey:JPushKey
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];
    
    //[JPUSHService setupWithOption:launchOptions]; 弃用
    return;
}

///第一步
- (void)setupWithOptions:(NSDictionary *)launchOptions uuidString:(NSString *)uuidString
{
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0)
    {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
        JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
        entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
        [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
    }
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1
    // ios8之后可以自定义category
     else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0)
    {
        // 可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    }
    else
    {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < __IPHONE_8_0
        // ios8之前 categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
#endif
    }
#else
    // categories 必须为nil
    [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)
                                       categories:nil];
#endif
    
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:JPushKey
                          channel:@"App Store"
                 apsForProduction:YES
            advertisingIdentifier:nil];

    
    //2.1.9版本新增获取registration id block接口。
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
        if(resCode == 0){
            NSLog(@"registrationID获取成功：%@",registrationID);
            
            NSString *strUrl = [uuidString stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            NSLog(@"uuidString:%@",strUrl);
            
            [JPUSHService setAlias:strUrl  callbackSelector:nil object:nil];
        }//7C3129208DB44A399BDCAEF0729AA780
        else
        {
            NSLog(@"registrationID获取失败，code：%d",resCode);
        }
    }];
    return;
}

+ (void)registerDeviceToken:(NSData *)deviceToken
{
    [JPUSHService registerDeviceToken:deviceToken];
    return;
}



+ (void)handleRemoteNotification:(NSDictionary *)userInfo completion:(void (^)(UIBackgroundFetchResult))completion {
    [JPUSHService handleRemoteNotification:userInfo];
    
    if (completion)
    {
        completion(UIBackgroundFetchResultNewData);
    }
    return;
}

+ (void)showLocalNotificationAtFront:(UILocalNotification *)notification
{
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
    return;  
}

+ (void)uploadToJpushAlias:(NSString *)alias andToServier:(BOOL)isServer;
{
    [JPUSHService setTags:nil alias:alias fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias)
    {
        
        NSLog(@"[向] -> [JPush] -> [上传] -> [别名] -> [成功]! —> [返回结果 = %zi] \n [iTags = %@] \n [别名Alias =%@ ]\n", iResCode, iTags, iAlias);
    }];
}
/**
 *
 * 1 日志发送  你有新的日志点评
 * 2 点评日志  你的日志已被点评
 * 3 日志回复  你有新的日志回复
 
 * 4 审批发送  你有新的审批复
 * 5 点评审批  你的审批已被批复
 * 6 审批回复  你有新的审批回复
 
 * 7 审批发送  你有新的日志点评
 * 8 点评审批  你的日志已被点评
 * 9 点评审批  你的日志已被点评
 
 * 10 审批发送  你有新的日志点评
 * 11 点评审批  你的日志已被点评
 * 12 点评审批  你的日志已被点评

 *
***/
+ (void)uploadToServerAlias:(NSString *)alias push_status:(NSString *)push_status;
{
    NSMutableDictionary *dic_M = [[NSMutableDictionary alloc] init];
    
    [dic_M setValue:@(30) forKey:@"CODE"];
    
    [dic_M setValue:alias forKey:@"alias"];
    
    [dic_M setValue:push_status forKey:@"push_status"];
    /*
    [[HelpDownloader shared] startRequest:Erp_Login withbody:dic_M  isNetWorkLonging:NO completion:^(id data, int kk)
     {
         if ([[data objectForKey:@"msgcode"] integerValue] == 1)
         {
             NSLog(@"[向] -> [欣窝] -> [发送] -> [别名] -> [成功]!");
         }
         else
         {
             NSLog(@"[向] -> [欣窝] -> [发送] -> [别名] -> [失败]!");
         }
     }];
     */
}










#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#pragma mark- JPUSHRegisterDelegate
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    NSDictionary * userInfo = notification.request.content.userInfo;
    
    UNNotificationRequest *request = notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content; // 收到推送的消息内容
    
    NSNumber *badge = content.badge;  // 推送消息的角标
    NSString *body = content.body;    // 推送消息体
    UNNotificationSound *sound = content.sound;  // 推送消息的声音
    NSString *subtitle = content.subtitle;  // 推送消息的副标题
    NSString *title = content.title;  // 推送消息的标题
    
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 前台收到远程通知:%@", [NSString logDic:userInfo]);
        
        //        [rootViewController addNotificationCount];
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 前台收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以设置
}

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    UNNotificationRequest *request = response.notification.request; // 收到推送的请求
    UNNotificationContent *content = request.content;               // 收到推送的消息内容
    
    NSNumber *badge = content.badge;                                // 推送消息的角标
    NSString *body = content.body;                                  // 推送消息体
    UNNotificationSound *sound = content.sound;                     // 推送消息的声音
    NSString *subtitle = content.subtitle;                          // 推送消息的副标题
    NSString *title = content.title;                                // 推送消息的标题
    
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        NSLog(@"iOS10 收到远程通知:%@", [NSString logDic:userInfo]);
      
        
        
    }
    else {
        // 判断为本地通知
        NSLog(@"iOS10 收到本地通知:{\nbody:%@，\ntitle:%@,\nsubtitle:%@,\nbadge：%@，\nsound：%@，\nuserInfo：%@\n}",body,title,subtitle,badge,sound,userInfo);
    }
    
    completionHandler();  // 系统要求执行这个方法
}
#endif













@end
